from bson import ObjectId
from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')
db = client['test']
book_collection = db['book']
reading_analysis_collection = db['reading_analysis']

def popular_recommendations(user_id=None):
    # 1. 从reading_analysis获取最新的分析数据
    analysis_data = reading_analysis_collection.find_one(
        {},
        sort=[('generated_at', -1)]  # 获取最新的分析结果
    )

    if not analysis_data or 'popular_books' not in analysis_data:
        return []

    # 2. 获取热门图书ID列表
    popular_book_ids = [book['id'] for book in analysis_data['popular_books']]

    if not popular_book_ids:
        return []

    # 3. 根据ID列表从book集合随机抽取10本图书信息
    books = list(book_collection.aggregate([
        {"$match": {"_id": {"$in": [ObjectId(bid) for bid in popular_book_ids]}}},
        {"$sample": {"size": 10}}
    ]))

    # 4. 合并分析数据和图书详情
    recommendations = []
    for book in books:
        for book_data in analysis_data['popular_books']:
            if str(book['_id']) == str(book_data['id']):
                recommendations.append({
                    '_id': str(book['_id']),
                    'title': book['title'],
                    'author': book['author'],
                    'cover': book['cover'],
                    'read_count': book_data.get('read_count', 0),
                    'collect_count': book_data.get('collect_count', 0),
                    'review_count': book_data.get('review_count', 0),
                    'unique_users': book_data.get('unique_users', 0)
                })
                break

    return recommendations